package cloudContact.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mybeans.factory.RollbackException;
import org.scribe.oauth.OAuthService;
import org.scribe.model.*;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.util.ServiceException;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import cloudContact.Common;
import cloudContact.FacebookManager;
import cloudContact.GoogleConstant;
import cloudContact.MyDAOException;
import cloudContact.SecurityManager;
import cloudContact.DAO.*;

/**
 * Servlet implementation class SyncFaceBook
 */
@WebServlet("/SyncFaceBook")
public class SyncFaceBook extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public SyncFaceBook() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("Start SyncFaceBook...");

		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		try {
			// Security check

			if (!SecurityManager.CheckAuthorization(request)) {
				out.println("Error: User is not authorized.");
				return;
			}

			HttpSession session = request.getSession();

			User user = UserDAO.getInstance().lookup(
					session.getAttribute("userId").toString());

			if (user == null) {
				out.println("Error: User is not found.");
				return;
			}
			
			String accessToken = user.getFacebookAccessToken();
			if (accessToken == null || accessToken.equals("")) {
				System.out.println("Not yet grant Facebook access.");
				out.println("Redirect:/CloudContact/FacebookOAuth");
				return;
			}

			GoogleOAuthParameters oauthParameters = GoogleConstant.getGoogleOAuthParameters(user.getGMailAccessToken(), user.getGMailAuthSecrete(), user.getUserId());
			
			String contactId = (String)request.getParameter("contactId");
			
			if (contactId == null || contactId.equals("")) {
				out.println("Error: parameter is not specified.");
				return;
			}
			
			contactId = contactId.replace("\\/", "/").replace("@", "%40");
			System.out.println("contact ID = " + contactId);
			
			GoogleContact contact = GoogleContactDAO.getInstanceForSession(session.getId(), oauthParameters).lookup(contactId);
			
			if (contact == null) {
				out.println("Error: contact not found.");
				return;
			}
			
			FacebookContactDAO dao = FacebookContactDAO.getInstance(session.getId(), "me", accessToken);
			
			ArrayList<FacebookContact> fbContacts = dao.getPossibleMatchedContacts(contact);

			Gson gson = new Gson();
			out.print(gson.toJson(fbContacts));
			
		} catch (MyDAOException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (RollbackException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (ServiceException e) {
			out.print(Common.CriticalErrorRaised(e));
		} catch (OAuthException e) {
			out.print(Common.CriticalErrorRaised(e));
		} finally {
			out.flush();
			out.close();
			System.out.println("Finish SyncFaceBook.");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
